package com.monkey.thread;

public class SequentialPrint {

    public static void main(String[] args) {
        PrintController controller = new PrintController();

        Thread threadA = new Thread(() -> controller.printA());
        Thread threadB = new Thread(() -> controller.printB());
        Thread threadC = new Thread(() -> controller.printC());

        // 启动线程
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

class PrintController {
    private int count = 0;
    private final Object lock = new Object();

    void printA() {
        while (true) {
            synchronized (lock) {
                if (count % 3 == 0 && count <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + count++);
                    lock.notifyAll();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    void printB() {
        while (true) {
            synchronized (lock) {
                if (count % 3 == 1 && count <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + count++);
                    lock.notifyAll();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    void printC() {
        while (true) {
            synchronized (lock) {
                if (count % 3 == 2 && count <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + count++);
                    lock.notifyAll();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
